﻿using System;
using System.Collections.Generic;
using System.Web;


namespace CCPSIP.Group
{
    /// <summary>CCPSIP_017：新增聊天群組 API</summary>
    /// idHeader = 裝置 UUID 前八碼。iOS 請使用 [CCPCrypto getIdHeader] 呼叫。
    /// checkcode = 裝置限時驗證碼。iOS 請使用 [CCPCrypto getCheckcode] 呼叫。
    /// GroupID = Host 產生的群組ID。
    /// GroupName = 群組名稱。
    /// Members = 群組成員帳號字串，帳號間以","分隔。

    public class new_group : IHttpHandler
    {
        private static string[] mSeparator = { "," };


        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";

            try
            {
                //【01】取得POST參數，驗證身分
                //
                string idHeader = req.Form["idHeader"];
                string checkcode = req.Form["checkcode"];
                string ClientGID = req.Form["GroupID"];  //Client端的群組ID
                string GroupName = req.Form["GroupName"];//群組名稱

                List<string> Members = new List<string>();//群組成員帳號List

                SipUserInfo userInfo = SipKit.GetUserInfo(idHeader, checkcode, req);
                if (userInfo == null)
                {
                    throw new Exception("Error_01: Cannot identify this device");//無法識別此裝置
                }

                try
                {
                    ClientGID = ClientGID.Trim().ToUpper();
                    if (!SipKit.isGroupID(ClientGID))
                    {
                        throw new Exception();//群組ID須為特定開頭
                    }
                    GroupName = ChrisKit.Substr(GroupName.Trim(), 0, 30);


                    //【02】整理成員帳號List
                    //
                    HashSet<string> memberSet = new HashSet<string>();
                    string[] mArray = req.Form["Members"].Split(mSeparator, StringSplitOptions.RemoveEmptyEntries);

                    for (int i = 0; i < mArray.Length; i++)
                    {
                        string member = mArray[i].Trim();
                        memberSet.Add(member);
                    }
                    memberSet.Add(userInfo.SIP_Num);

                    if (memberSet.Count < 3)
                    {
                        throw new Exception();//不滿三個人不可成立群組
                    }

                    Members.AddRange(memberSet);
                    Members.Sort();
                }
                catch
                {
                    throw new Exception("Error_02: Parameter Error");//參數錯誤
                }


                //【03】新增聊天群組
                // TODO:2014/12/9 檢查群組是否存在
                int GroupID = 0;
                if (OracleKitGroup.IsGroupExist(ClientGID) == false)
                    GroupID = OracleKitGroup.NewGroupChat(userInfo, reqTime, ClientGID, GroupName, Members.ToArray());
                else
                    throw new Exception("ERROR_01: The group is already Exist.");   //此Group已存在

                //【97】通知Push Service
                //
                PushKit.WakePushAsync(PushKit.PushType.Msg);


                //【98】傳送 Windows CCP MSG 通知
                //
                string notifyMsg = string.Format("{0} 成立了群組「{1}」", userInfo.CustomName, GroupName);
                foreach (string member in Members)
                {
                    if (SipKit.isHQMobileExt(member))
                        MSGKit.SendTextHQAsync(member, notifyMsg);
                }


                //【99】回傳結果
                //
                resultStr = "OK";
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
            }
            finally
            {
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
                resp.Flush();
                resp.Close();
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}
